package com.sinsz.c.context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * spring上下文获取
 * @author chenjianbo
 * @date 2017/7/17
 */
public class SpringHolderUtil implements ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(SpringHolderUtil.class);

    private static SpringHolderUtil holder = new SpringHolderUtil();

    private SpringHolderUtil() {
    }

    public static SpringHolderUtil instance() {
        return holder;
    }

    private ApplicationContext applicationContext = null;

    /**
     * 设置上下文
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        instance().applicationContext = applicationContext;
    }

    /**
     * 检查是否已经注入上下文
     */
    private void checkApplicationContext() {
        if(applicationContext == null) {
            throw new IllegalStateException("请开启框架注解@EnableBxfs");
        }
    }

    /**
     * 获取上下文
     * @return
     */
    public ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    /**
     * 通过class获取Bean
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T getBean(Class<T> clazz){
        checkApplicationContext();
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name获取 Bean
     * @param name
     * @return
     */
    public Object getBean(String name){
        checkApplicationContext();
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T getBean(String name,Class<T> clazz){
        checkApplicationContext();
        return getApplicationContext().getBean(name, clazz);
    }

}